package org.jeecg.modules.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.SneakyThrows;
import org.jeecg.modules.entity.ChatgptTalkInfo;
import org.jeecg.modules.mapper.ChatgptTalkInfoMapper;
import org.jeecg.modules.service.IChatgptTalkInfoService;
import org.jeecg.modules.utils.TextToSound;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

import static org.jeecg.modules.utils.DateUtils.getOrderNo;

/**
 * @Description: chatgpt_talk_info
 * @Author: jeecg-boot
 * @Date:   2023-03-09
 * @Version: V1.0
 */
@Service
public class ChatgptTalkInfoServiceImpl extends ServiceImpl<ChatgptTalkInfoMapper, ChatgptTalkInfo> implements IChatgptTalkInfoService {

    @Autowired
    private ChatgptTalkInfoMapper chatgptTalkInfoMapper;


    private static final String API_KEY = "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";

    public String getConversationId(String sessionId){
        String conversationId = null;
        conversationId = chatgptTalkInfoMapper.getConversationId(sessionId);
        return conversationId;
    }

    @Override
    @SneakyThrows
    public String chatGPT(String prompt, String conversationId, String sessionId) {
        String apiKey = API_KEY;
        String url = "https://api.openai.com/v1/chat/completions";
        String response = generateText(prompt, apiKey, url,conversationId);
        JSONObject jsonObject = new JSONObject(response);
        JSONArray choices = jsonObject.getJSONArray("choices");
        conversationId = jsonObject.getString("id");
        JSONObject message = choices.getJSONObject(0).getJSONObject("message");
        String text = message.getString("content");
        QueryWrapper<ChatgptTalkInfo> chatgptTalkInfoQueryWrapper = new QueryWrapper<>();
        chatgptTalkInfoQueryWrapper.eq("session_id",sessionId);
        Long gptCount = chatgptTalkInfoMapper.selectCount(chatgptTalkInfoQueryWrapper);
        if(gptCount > 0){
            log.debug("会话已存在");
        }else{
            ChatgptTalkInfo chatGptTalkDTO = new ChatgptTalkInfo();
            chatGptTalkDTO.setId(getOrderNo().intValue());
            chatGptTalkDTO.setUsertext(prompt);
            chatGptTalkDTO.setRebottext(text);
            chatGptTalkDTO.setSessionId(sessionId);
            chatGptTalkDTO.setConversationid(conversationId);
            chatgptTalkInfoMapper.insert(chatGptTalkDTO);
        }
        return text;
    }


    private String generateText(String prompt, String apiKey, String url,String conversationId) throws IOException {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod("POST");
        connection.setConnectTimeout(5000);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Authorization", "Bearer " + apiKey);
        connection.setRequestProperty("Conversation-Id", conversationId);
        connection.setDoOutput(true);
        String engine = "gpt-3.5-turbo";
        String text = "{\"role\": \"user\", \"content\": \""+prompt+"\"}";
        int maxTokens = 2048;
        double temperature = 0.0;
        String requestBody = "{\"model\": \"" + engine + "\", \"messages\": [" + text + "], \"max_tokens\": " + maxTokens + ", \"temperature\": " + temperature + "}";
        connection.getOutputStream().write(requestBody.getBytes(StandardCharsets.UTF_8));
        Scanner scanner = new Scanner(connection.getInputStream());
        String response = scanner.useDelimiter("\\A").next();
        scanner.close();
        return response;
    }

    @SneakyThrows
    public String tts(String inText){
        String soundUrl = null;
        soundUrl = TextToSound.Tts(inText);
        return soundUrl;
    }
}
